package com.grupoconstruobras.sigo.exhumaciones.ui.datamodel;

import com.grupoconstruobras.sigo.datatransfer.ResultSet;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;

import org.richfaces.component.SortOrder;

public class DataModelMb<T> implements IDataModelMb<T> {
  private Map<String, SortOrder> sortOrders;
  private Map<String, Object> filterValues;
  private String sortProperty;
  private IDataModelFactory<T> factory;
  private Object[] parameters;
  private ResultSet<T> result;
  private IDataModelCallback<T> callback;

  public DataModelMb(Map<String, Object> filterValues, Map<String, SortOrder> sortOrders,
      IDataModelFactory<T> factory) {
    this.filterValues = filterValues;
    this.sortOrders = sortOrders;
    this.factory = factory;
  }

  @Override
  public void setSortProperty(String sortPropety) {
    this.sortProperty = sortPropety;
  }

  @Override
  public String getSortProperty() {
    return sortProperty;
  }

  @Override
  public Map<String, SortOrder> getSortOrders() {
    return sortOrders;
  }

  @Override
  public void toggleSort() {
    for (Entry<String, SortOrder> entry : sortOrders.entrySet()) {
      SortOrder newOrder;

      if (entry.getKey().equals(sortProperty)) {
        if (entry.getValue() == SortOrder.ascending) {
          newOrder = SortOrder.descending;
        }
        else {
          newOrder = SortOrder.ascending;
        }
      }
      else {
        newOrder = SortOrder.unsorted;
      }
      entry.setValue(newOrder);
    }
  }

  @Override
  public ExtendedDataModel<T> getDataModel() {
    ExtendedDataModel<T> dm = factory.newInstance(callback, parameters);
    if(dm != null)
    	result = dm.getResult();
    else 
    	result = new ResultSet<T>(0, Collections.unmodifiableList(new ArrayList<T>()));
    return dm;
  }

  @Override
  public Map<String, Object> getFilterValues() {
    return filterValues;
  }

  @Override
  public void setParameters(Object... parameters) {
    this.parameters = parameters;
  }

	@Override
	public ResultSet<T> getResult() {
		return result;
	}
	
	public void setCallback(IDataModelCallback<T> callback) {
		this.callback = callback;
	}

}
